from constant.param_config import getConfigPath
from utils.db_util import SqliteTool
import json
import re


class SqlTest():

    regularList = [
        "黄金操作(策略|思路|建议)[^;；。！!]*[;；。！!]",
        "(综合来看|综上所述|综合考虑)[^;；。！!]*[;；。！!]",
        "(?:黄金)?晚间[(操作)|(交易)][^!！;；。]*[!！;；。]",
        "日内短线[^！!。]*[^！!。]",
        "日内操作[^！!。]*[^！!。]",
        "今日晚间[^！!。]*[^！!。]",
        "黄金晚间[^！!。：]*[^！!。：]",
        "操作建议[^！!]*策略[^！!。]*[！!。]",
        "操作建议[^！!。]*[^！!。]",
        "策略建议[^！!。]*[^！!。]",
        "今日操作[^！!。]*[^！!。]",
        "(对于晚间，|对于今日，)[^！!。]*[^！!。]",
        "后市操作上[^！!。]*[^！!。]",
        "黄金[^！!]*策略[^！!。]*[！!。]",
        "[，！!。][^，！!；;。]*不破做空[^！!；;]*不破做多[^！!；;。]*[！!；;。]",
        "(操作[上]?建议|操作思路上|操作方面)[^!！;；。]*[!！;；。]",
        "今日：[^！!。]*[！!。]",
        "策略一：[^；]*[；]",
        "日内[^！!。]*(空|多|损|目标)[^！!。]*(空|多|损|目标)[^！!。]*(空|多|损|目标)*[^！!。]",
        "今日而言[^!！;；。]*上方[^!！;；]*下方[^!！;；。]*[!！;；。]",
        "今天[^！!；;]*[空|多][^！!；;]*[！!；;。]",
        "[^！!。]*(附近多|止损|目标)[^！!。]*(附近多|止损|目标)[^！!。]*(目标|附近多|止损)[^！!。]",
        "[^！!。]*(关注|止损|入场|支撑|压力)[^！!。]*(关注|止损|入场|支撑|压力)[^！!。]*(入场|关注|止损|支撑|压力)*[^！!。]",
    ]

    sellRegularList = [
        "反弹至\d{4}-\d{4}[^;；。！!，，]*(做)?空",
        "\d{4}-\d{4}[^;；。！!，，]*(做)?空",
        "\d{4}-\d{2}[^;；。！!，，]*(做)?空",
        "\d{4}[^;；。！!，，]*(做)?空",
        "\d{4}-\d{4}[^;；。！!，，((]*(阻力|卖出)",
        "\d{4}-\d{2}[^;；。！!，，]*阻力",
        "\d{4}[^;；。！!，，:：（(]*(卖|下游|跌|阻力)",
        "[^，！!；;。]*空单[^;；。！!，，]*进场[^;；。！!，，]*\d{4}-\d{4}",
        "(压力|看下方)[^;；。！!，，]*\d{4}-\d{4}",
        "做空[^;；。！!，，]*\d{4}-\d{2}",
        "(做空|阻力)[^;；。！!，，]*\d{4}",
        "上方[^;；。！!，，]*\d{4}不破",
        "\d{4}[^;；。！!，，]*不破看(下行|跌)",
    ]
    buyRegularList = [
        "反弹至\d{4}-\d{4}[^;；。！!，，]*(做)?多",
        "\d{4}-\d{4}[^;；。！!，，]*(做)?多",
        "\d{4}-\d{2}[^;；。！!，，]*(做)?多",
        "\d{4}[^;；。！!，，]*(做)?多",
        "\d{4}-\d{4}[^;；。！!，，（(]*(支撑|买)",
        "\d{4}-\d{2}[^;；。！!，，]*支撑",
        "\d{4}[^;；。！!，，:：（(]*(买|上游|涨|支撑)",
        "[^，！!；;。]*多单[^;；。！!，，]*进场[^;；。！!，，]*\d{4}-\d{4}",
        "(支撑|看上方)[^;；。！!，，]*\d{4}-\d{4}",
        "做多[^;；。！!，，]*\d{4}-\d{2}",
        "(做多|支撑)[^;；。！!，，]*\d{4}",
        "下方[^;；。！!，，]*\d{4}不破",
        "\d{4}[^;；。！!，，]*不破看(上行|涨)",
    ]
    stopLossRegularList = [
        "(止损|保护|防守)\d{4}",
        "sun[^;；。！!，，]*\d{1}个点",
    ]
    takeProfitRegularList = [
        "(目标|下看)[^;；。！!，，]*\d{4}-\d{4}一线",
        "(目标|下看)[^;；。！!，，]*\d{4}-\d{4}",
        "(目标|下看)[^;；。！!，，]*\d{4}",
        "(空|多)到[^;；。！!，，]*\d{4}",
    ]

    coreBuy = ["多为主", "涨为主", "空为辅", "先多后空", "主多", "看多"]
    coreSell = ["空为主", "多为辅", "先空后多", "主空", "看空"]

    immediately = ["现价[^！!。，]\d{4}[^！!。，](多|空)"]

    noStrategy = []
    strategyInfoList = []
    coreResult = None
    timePoint = [9, 12, 15, 18, 21]

    maxStrategyLength = 300

    webSite = "https://pinglun.fx678.com"
    articePath = webSite + "/category/103?page="
    lastDay = -1
    page = 1

    def __init__(self):
        dbPath = getConfigPath() + "back.db"
        self.sqlite = SqliteTool(dbPath=dbPath)

    def immediatelyTrade(self):
        """
        现价单
        """
        articleList = self.sqlite.query_many(
            "SELECT id,article FROM article_table where state=1")

        textList = []
        if articleList is not None and len(articleList) != 0:
            for item in articleList:
                result = re.search(
                    "现价[^！!。，]*(\d{4})*[^！!。，](多|空｜涨|跌)", item[1], re.S)
                if result:
                    value = result.group()
                    textList.append(value)
        print("")

    def regularStrategy(self):
        """
        3、正则匹配交易策略
        """

        articleList = self.sqlite.query_many(
            "SELECT id,article FROM article_table where state=1")

        if articleList is not None and len(articleList) != 0:
            for item in articleList:
                reResult = []
                for index in range(0, len(self.regularList)):
                    result_ti = re.search(
                        self.regularList[index], item[1], re.S)
                    if result_ti and len(result_ti.group()) < self.maxStrategyLength:
                        reslit = result_ti.group()

                        if ("策略一" in reslit and "策略二" not in reslit) or ("策略1" in reslit and "策略2" not in reslit):
                            childStr = item[1][item[1].find(
                                reslit)+len(reslit):]
                            if childStr != "" and childStr != None:
                                childResult = re.search(
                                    "(策略二|策略2)[^！!。；]*[^！!。；]", childStr, re.S)
                                if childResult:
                                    reslit = reslit+childResult.group()

                        childResult = re.search("\d{4}", reslit, re.S)
                        if childResult:
                            reResult.append(reslit)

                if len(reResult) != 0:
                    minLengthStr = min(reResult, key=len)
                    self.sqlite.operate_one(
                        "update article_table set strategy=? where id=?",
                        (minLengthStr, item[0]))

    def regularViewpoint(self):
        """
        4、匹配交易观点
        """

        strategys = self.sqlite.query_many(
            "SELECT id,strategy FROM article_table WHERE strategy != ''")

        if strategys is not None and len(strategys) != 0:
            for item in strategys:
                childStrategy = []
                for index in range(0, len(self.sellRegularList)):
                    sell = {}
                    result = re.search(
                        self.sellRegularList[index], item[1], re.S)
                    if result:
                        sell["sell"] = self.formatePrice(result.group())
                        for spItem in self.stopLossRegularList:
                            spResult = re.search(spItem, item[1], re.S)
                            if spResult:
                                reslit = spResult.group()
                                sell["sp"] = self.formatePrice(reslit)
                                break
                        for tpItem in self.takeProfitRegularList:
                            tpResult = re.search(tpItem, item[1], re.S)
                            if tpResult:
                                reslit = tpResult.group()
                                sell["tp"] = self.formatePrice(reslit)
                                break
                    if len(sell) != 0:
                        childStrategy.append(sell)
                        break
                    elif index == len(self.sellRegularList) - 1:
                        break

                for index in range(0, len(self.buyRegularList)):
                    buy = {}
                    result = re.search(
                        self.buyRegularList[index], item[1], re.S)
                    if result:
                        buy["buy"] = self.formatePrice(result.group())
                        for spItem in self.stopLossRegularList:
                            spResult = re.search(spItem, item[1], re.S)
                            if spResult:
                                reslit = spResult.group()
                                buy["sp"] = self.formatePrice(reslit)
                                break
                        for tpItem in self.takeProfitRegularList:
                            tpResult = re.search(tpItem, item[1], re.S)
                            if tpResult:
                                reslit = tpResult.group()
                                buy["tp"] = self.formatePrice(reslit)
                                break
                    if len(buy) != 0:
                        childStrategy.append(buy)
                        break
                    elif index == len(self.buyRegularList) - 1:
                        break

                if len(childStrategy) != 0:
                    info = self.formatePriceList([childStrategy])
                    self.strategyInfoList.append(info[0])
                    self.sqlite.operate_one(
                        "update article_table set viewpoint=? where id=?",
                        (json.dumps(info[0]), item[0]))
                else:
                    self.noStrategy.append(item[1])
                    self.sqlite.operate_one(
                        "update article_table set viewpoint=? where id=?",
                        ("", item[0]))

    def formatePrice(self, source):
        """
        获取价格
        """
        result = re.compile(r'\d{4}').findall(source)
        if len(result) != 0:
            return "、".join(result)
        return ""

    def formatePriceList(self, article):
        """
        剔除不符合规范的价格
        """
        for child in article:
            sellIndex = [
                index for index in range(0, len(child))
                if "sell" in child[index]
            ]
            buyIndex = [
                index for index in range(0, len(child))
                if "buy" in child[index]
            ]

            if len(sellIndex) != 0:
                sellInfo = child[sellIndex[0]]
                splitSell = [int(item) for item in sellInfo["sell"].split("、")]
                if "sp" in sellInfo and sellInfo["sp"] != "":
                    spValue = [int(item) for item in sellInfo["sp"].split("、")]
                    if all(a < b for a, b in zip(splitSell, spValue)) is False:
                        sellInfo.pop("sp")
                if "tp" in sellInfo and sellInfo["tp"] != "":
                    spliteTp = [
                        int(item) for item in sellInfo["tp"].split("、")
                    ]
                    if all(b < a
                           for a, b in zip(splitSell, spliteTp)) is False:
                        sellInfo.pop("tp")

            if len(buyIndex) != 0:
                buyInfo = child[buyIndex[0]]
                splitBuy = [int(item) for item in buyInfo["buy"].split("、")]
                if "sp" in buyInfo and buyInfo["sp"] != "":
                    spValue = [int(item) for item in buyInfo["sp"].split("、")]
                    if all(b < a for a, b in zip(splitBuy, spValue)) is False:
                        buyInfo.pop("sp")
                if "tp" in buyInfo and buyInfo["tp"] != "":
                    spliteTp = [int(item) for item in buyInfo["tp"].split("、")]
                    if all(a < b for a, b in zip(splitBuy, spliteTp)) is False:
                        buyInfo.pop("tp")
        return article
